<template>
  <div class="supply">
    <el-button type="text" size="small" @click="cancelBindSupply" v-if="type === 0">取消绑定</el-button>
    <el-button type="text" size="small" @click="goBindSupply" v-if="type === 1">绑定</el-button>
    <el-dialog
      title="供应商商品列表"
      :visible.sync="dialogVisible"
      width="90%"
      :before-close="handleClose"
      append-to-body

    >
      <div class="table">
        <!--  头部搜索    -->
        <div class="search-wrap">
          <el-col style="line-height: 40px;width: 90px;">选择供应商：</el-col>
          <div class="merchant">
            <el-select
              filterable
              remote
              :remote-method="remoteMerchant"
              v-model="merchantId"
              @change="changeMerchant"
              placeholder="请选择">
              <el-option
                v-for="(item,index) in merchantList"
                :key="index"
                :label="item.merchantName"
                @change="changeMerchant"
                :value="item.merchantId"/>
            </el-select>
          </div>
          <el-col :span="4" style="line-height: 40px;width: 80px;">选择店铺：</el-col>
          <div class="shop">
            <el-select
              filterable
              remote
              :remote-method="remoteShop"
              v-model="shopId"
              @change="changeShop"
              placeholder="请选择">
              <el-option
                v-for="(item,index) in shopList"
                :key="index"
                :label="item.name"
                :value="item.shopId"/>
            </el-select>
          </div>
          <el-input
            placeholder="请输入需要搜索的商品名称"
            prefix-icon="el-icon-search"
            style="display:inline-block;width: 250px;margin-left: 20px"
            v-model="goodsName"
            @change="searchGoods"
            clearable
          >
          </el-input>
          <el-button type="default" size="small" @click="resetGoodsList" style="height: 36px;margin-left: 20px">清除条件</el-button>
        </div>
        <el-container>
          <!-- 侧边栏 -->
          <el-aside width="220px" class="aside-nav">
            <avue-tree
              :option="categoryOption"
              :data="goodsCategories"
              @node-click="getCategoryGoods"
            >
            </avue-tree>
          </el-aside>
          <!-- 表格区域 -->
          <el-main>
            <avue-crud ref="crud" :data="tableData" :option="tableOption">
              <template slot-scope="scope" slot="handle">
                <el-button type="text" size="small" @click="bindSupply(scope.row)">绑定</el-button>
              </template>
            </avue-crud>
          </el-main>
        </el-container>
        <el-footer style="margin-top: 10px">
          <div class="pagination">
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                           :current-page.sync="currentPage" :page-sizes="[10, 20, 40, 60]" :page-size="10"
                           background :layout="layout" :total="totalCount">
            </el-pagination>
          </div>
        </el-footer>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {getmerchantList} from "../../../api/supply/supplier"
  import {fetchList} from "../../../api/manage/shop";
  import {getCategoryTree} from "../../../api/goods/goodscategory";
  import {getgoodslist, bindgoods, cancelrelategoods} from "../../../api/supply/supply_goods_info"
  import {supplyOption} from "../../../const/crud/supply/supplygoodsoption"

  export default {
    name: "v-relationSupply",
    data() {
      return {
        dialogVisible: false,
        goodsName: '',
        merchantList: [],
        shopList: [],
        merchantId: '',
        shopId:'',
        totalCount: 10,
        currentPage: 1,
        pageSize: 10,
        categoryId: '',
        goodsCategories: [],
        tableData: [],
        tableOption: supplyOption,
        layout: "total, sizes, prev, pager, next, jumper",
        categoryOption: {
          defaultExpandAll:true,
          addBtn: false,
          props:{
            label: 'name',
            value: 'id',
            children: 'children'
          }
        }
      }
    },
    props: {
      // 平台商品信息
      row: {
        type: Object,
        default() {
          return {}
        }
      },
      // 供应商数据
      Supply: {
        type: Object,
        default() {
          return {}
        }
      },
      // 是否绑定
      type: {
        type: Number,
        default() {
          return 1
        }
      }
    },
    methods: {
      //获取供应商列表
      getMerchantList(param = {}) {
        getmerchantList(param).then(res => {
          this.merchantList = res.data.data.records
          this.merchantId = res.data.data.records[0].merchantId
          this.getShopList()
        })
      },
      remoteMerchant(name = null) {
        let query = {
          merchantName: name,
          status: 2
        };
        getmerchantList(query).then(res => {
          this.merchantList = res.data.data.records;
        });
      },
      //改变merchantId
      changeMerchant() {
        let params = {
          current: this.currentPage,
          size: this.pageSize,
          status: 2,
          merchantId: this.merchantId,
          name: name
        }
        fetchList(params).then(res => {
          // console.log(res.data.data.records);
          this.shopList = res.data.data.records
          if (res.data.data.records.length == 0) {
            this.$message.warning("没有店铺")
            this.shopId = ''
            this.tableData = []
            this.goodsCategories = []
          }
          setTimeout(() => {
            this.shopId = this.shopList[0].shopId
            this.categoryId = ''
            this.getGoodsList()
            this.getGoodsCategoryList()
          },)
        })
      },
      //获取店铺列表
      getShopList() {
        let params = {}
        params.current = this.currentPage
        params.size = this.pageSize
        params.status = 2
        params.merchantId = this.merchantId
        fetchList(params).then(res => {
          this.shopList = res.data.data.records
          this.shopId = res.data.data.records[0].shopId
          this.getGoodsCategoryList()
          this.getGoodsList()
        })
      },
      remoteShop(name = null) {
        let params = {
          current: this.currentPage,
          size: this.pageSize,
          status: 2,
          merchantId: this.merchantId,
          name: name
        }
        fetchList(params).then(res => {
          this.shopList = res.data.data.records
        })
      },
      // 获取商品分类列表
      getGoodsCategoryList(param = {}) {
        getCategoryTree({shopId: this.shopId}).then(res => {
          this.goodsCategories = res.data.data
        })
      },
      // 获取分类商品
      getCategoryGoods(categoryId) {
        const params = {}
        params.current = this.currentPage
        this.categoryId = categoryId.id
        this.getGoodsList()
      },
      //获取商品
      getGoodsList(params) {
        params = {
          current: this.currentPage,
          size: this.pageSize,
          shopId: this.shopId,
          categoryId: this.categoryId,
          goodsName: this.goodsName
        }
        console.log(this.categoryId);
        getgoodslist(params).then(res => {
          this.totalCount = res.data.data.total
          this.tableData = res.data.data.records
        })
      },
      //改变shopID
      changeShop() {
        this.getGoodsList()
        this.getGoodsCategoryList()
      },
      resetGoodsList() {
        this.categoryId = ''
        this.goodsName = ''
        this.getGoodsList()
      },
      //打开弹框
      cancelBindSupply() {
        let params = {
          shopId: this.Supply.shopId,
          supplyModelId: this.Supply.modelId,
          supplyGoodsId: this.Supply.goodsId,
          platformGoodsId: this.row.goodsId,
          platformModelId: this.row.modelId
        }
        cancelrelategoods(params).then(res => {
          console.log("取消成功");
          this.$message.success("取消成功")
          this.$emit("refresh")
          this.dialogVisible = false
        }).catch(err => {
          val.relationType = "1"
          this.$message.error("取消失败")
        })
      },
      //去关联
      goBindSupply() {
        this.getMerchantList({status: 2})
        this.dialogVisible = true
      },

      handleClose() {
        this.dialogVisible = false
      },
      //  搜索框
      searchGoods(val) {
        this.goodsName = val
        this.getGoodsList()
      },
      //分页——跳转页
      handleSizeChange(size) {
        this.pageSize = size
        this.getGoodsList()
      },
      handleCurrentChange(page) {
        this.currentPage = page
        this.getGoodsList()
      },
      bindSupply(val) {
        let params = {
          shopId: this.shopId,
          // row是平台商品信息
          platformGoodsId: this.row.goodsId,
          platformModelId: this.row.modelId,
          supplyGoodsId: val.goodsId,
          supplyModelId: val.modelId
        }
        bindgoods(params).then(res => {
          this.$message.success("关联成功")
          this.dialogVisible = false
          this.$emit("refresh")
        }).catch(err => {
          this.$message.error("关联失败")
        })
      }
    }
  }
</script>

<style scoped>
  .search-wrap {
    text-align: right;
    position: relative;
    display: flex;
    padding-top: 10px;
  }

  .merchant, .shop {
    display: flex;
    width: 150px;
  }

  .aside-nav {
    height: 400px;
    text-align: left;
    /*margin-top: 20px;*/
  }
</style>
